//aop切面对日志进行处理

package com.wzy.wzyblog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by limi on 2017/10/13.
 */
//切面注解，生成代理对象
@Aspect
//开启组件扫描，被增强的类
@Component
public class LogAspect {
//日志记录器
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

// 设定为切面      切面拦截： 任何  包              类  方法（任何参数）     web包下的请求都会被切面拦截
    @Pointcut("execution(* com.wzy.wzyblog.web.*.*(..))")
    public void log() {}

//切面之前定义内容
    @Before("log()")
//                         获取拦截方法参数
    public void doBefore(JoinPoint joinPoint) {
//通过ServletRequestAttributes的RequestContextHolder.getRequestAttributes()获取HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        通过HttpServletRequest获取url和ip
        HttpServletRequest request = attributes.getRequest();
//                       stringbuffer类型要tostring
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
//                                                          获取类名               .                             方法名
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
//                               获取请求参数
        Object[] args = joinPoint.getArgs();
//        构造对象
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
//        输出对象
        logger.info("Request : {}", requestLog);
    }
//请求方法之后
    @After("log()")
    public void doAfter() {
//        logger.info("--------doAfter--------");
    }
//请求方法返回最后结果      根据参数捕获拦截的方法返回的内容    切面
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterRuturn(Object result) {
//捕获返回内容
        logger.info("Result : {}", result);
    }
//把对象封装到内部，定义一个类
    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;
//构造器
        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }
//toString
        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
